package com.qzsoft.system.modules.zhjdlogin.controller;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.qzsoft.jeemis.common.utils.KeyStoreUtil;
import com.qzsoft.jeemis.common.utils.Result;
import com.qzsoft.jeemis.common.validator.ValidatorUtils;
import com.qzsoft.jeemis.platform.security.dto.LoginDTO;
import com.qzsoft.jeemis.platform.security.service.BasicLoginService;
import com.qzsoft.jeemis.platform.security.service.CaptchaService;
import com.qzsoft.system.modules.zhjdlogin.dao.PasswordValidDao;

import io.swagger.annotations.ApiOperation;

/**
 * @ClassName ZhjdLoginController
 * @Description 智慧基地养护登录
 * @author linhuawei
 * @since 2022-06-30
 */
@RestController
public class ZhjdLoginController {

    @Resource(name = "${jeemis.login.captchaType:SpecCaptcha}")
    private CaptchaService captchaService;

    @Value("${jeemis.login.captchaEnable:true}")
    private Boolean captchaEnable;

    @Autowired
    private BasicLoginService basicLoginService;

    @Autowired
    private PasswordValidDao passwordValidDao;

    @PostMapping({ "zhjdlogin" })
    @ApiOperation("登录")
    public Result login(HttpServletRequest request, @RequestBody LoginDTO login) {
        // 校验登录信息
        ValidatorUtils.validateEntity(login, new Class[0]);
        if (this.captchaEnable.booleanValue()) {
            boolean flag = this.captchaService.validate(login.getUuid(), login.getCaptcha());
            if (!flag) {
                return new Result().error(10007);
            }
        }

        // 获取登录信息
        Result result = this.basicLoginService.login(request, login);

        // 登录成功后验证密码信息
        if (0 == result.getCode()) {
            Map<String, Object> map = (Map<String, Object>) result.getData();
            Object userId = map.get("userId");
            String password = KeyStoreUtil.decryptStr(login.getPassword());
            map = passwordValidDao.validatePasswordAfterLoginSuccess(userId, password);
            String code = null == map.get("code") ? "" : map.get("code").toString();
            String msg = null == map.get("msg") ? "" : map.get("msg").toString();
            if (!"200".equals(code)) {
                result.setCode(107);
                result.setMsg(msg);
            }
        }
        return result;
    }

}
